package org.jeecg.modules.rental.init;

import cn.hutool.core.util.StrUtil;
import org.jeecg.common.annotation.EnumDict;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class EnumRegistrar {

    private final Map<String, Class<? extends Enum<?>>> DICT_POOL = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        ClassPathScanningCandidateComponentProvider scanner =
                new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(EnumDict.class));
        String[] basePackages = new String[]{"org.jeecg.modules.rental.enums"};
        for(String basePackage : basePackages ){
            for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) {
                try {
                    Class<?> clazz = Class.forName(candidate.getBeanClassName());
                    if (clazz.isEnum() && EnumDict.class.isAssignableFrom(clazz.getAnnotation(EnumDict.class).getClass())) {
                        EnumDict enumDict = clazz.getAnnotation(EnumDict.class);
                        String code = enumDict.code(); // 获取注解中的code值
                        String key = StrUtil.isNotBlank(code) ? code : clazz.getSimpleName();
                        DICT_POOL.put(key, (Class<? extends Enum<?>>) clazz);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 提供获取注册枚举的方法
    public Map<String, Class<? extends Enum<?>>> getRegisteredEnums() {
        return DICT_POOL;
    }
}